package com.app.controller.backstage;

//import com.app.conf.RedisService;

import com.app.conf.RedisService;
import com.app.model.AdminUserModel;
import com.app.service.AdminUserService;
import com.app.util.AESTool;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.AdminUserVo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;


@RestController
@Controller
public class AdminUserController {
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RedisService redisService;

    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        redisService.setStringKey(capText, capText);
        redisService.setExpire(capText,60, TimeUnit.SECONDS);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
    /**
     * 后台登录
     */
    @PostMapping("/userLogin")
    public Result<Object> userLogin(@RequestParam("userName") String userName,
                                    @RequestParam("password") String passWord,
                                    @RequestParam("code") String code) {

        String asePassWord = AESTool.dealAESEncrypt(passWord, "hwsc_pass");
        if (redisService.getStringKey(code) == null) {
            return Result.error(500,"验证码错误");
        } else {
            redisService.deleteKey(code);
        }
        AdminUserModel user = adminUserService.getUserByUserName(userName, asePassWord);
        if (user == null) {
            return Result.error(500,"用户名或密码错误");
        }
        String token = TokenUtils.sign(String.valueOf(user.getId()));
        AdminUserVo vo = new AdminUserVo();
        vo.setUser(user);
        vo.setToken(token);
        return Result.success(vo);
    }

    /**
     * 后台修改密码
     */
    @PostMapping("/updatePassWord")
    public Result<Object> userLogin(@RequestParam("pastPassWord") String pastPassWord,
                                    @RequestParam("newPassWord") String newPassWord,
                                    HttpServletRequest request
                                    ) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String asePassWord = AESTool.dealAESEncrypt(pastPassWord, "hwsc_pass");
        String newAsePassWord = AESTool.dealAESEncrypt(newPassWord, "hwsc_pass");
        if(!asePassWord.equals(user.getPassWord()))
        {
            return Result.error(500,"旧密码错误");
        } else if (newAsePassWord.equals(user.getPassWord())) {

            return Result.error(500,"新密码不能与旧密码一致");
        } else{
            user.setPassWord(AESTool.dealAESEncrypt(newPassWord, "hwsc_pass"));
            adminUserService.update(user);
            return Result.success("修改成功");
        }
    }
}